<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\GoodsShopcar;
use App\Models\GoodsAttribute;
use App\Models\Cart;
use Illuminate\Support\Facades\Storage;
use App\Models\Address;
use App\Models\Order;
use App\Models\OrdersGood;
use App\Models\Withdraw;
use App\Models\CaitCart;
use App\Models\RechargeRecord;
use EasyWeChat\Payment\Application;
use App\User;
use Omnipay\Omnipay;
class UserController extends Controller
{
    /**
     * 增加购物车
     * @param Request $request
     */
    public function addCart(Request $request)
    {
        $user = Auth::user();
        //判断是否存在该商品以及属性
        $info = GoodsAttribute::where('good_id', $request->goods_id)->find($request->goods_attr_id);
        if(!$info)
        {
            return ['status'=>0, 'msg' => translate('不存在该产品')];
        }
        $GoodsShopcar = new GoodsShopcar();
        $GoodsShopcar->user_id = $user->id;
        $GoodsShopcar->number = (int)$request->number;
        $GoodsShopcar->content = $request->detail;
        $GoodsShopcar->goods_id = (int)$request->goods_id;
        $GoodsShopcar->goods_attr_id = (int)$request->goods_attr_id;
        if($request->type == 1)$GoodsShopcar->status = 3;
        $GoodsShopcar->save();
        return ['status'=>1, 'id' => $GoodsShopcar->id];
    }
    /**
     * 购物车
     * @param Request $request
     */
    public function cart(Request $request)
    {
        if($request->isMethod('post'))
        {
            if($request->type == 'del')
            {
                $ids = $request->ids;
                if(!$ids)return ['status'=>0];

                GoodsShopcar::where('user_id', Auth::user()->id)->where('status', 1)->whereIn('id', $ids)->delete();
                return ['status'=>1];
            }
        }
        $pageList = GoodsShopcar::where('user_id', Auth::user()->id)->where('status', 1)->orderBy('id', 'desc')->get();
        return view('user.cart', compact('pageList'));
    }
    /**
     * 计算购物车商品价格
     * @param Request $request
     * @return number[]|string[]|\Illuminate\Contracts\Translation\Translator[]|NULL[]|number[]
     */
    public function getCal(Request $request)
    {
        $carts = $request->carts;
        if(!$carts || empty($carts))return ['status'=>0, translate('请选择商品')];

        $List = GoodsShopcar::whereIn('id', $carts)->get();
        $total = sumTotal($List);
        return ['status'=>1, 'total' => $total];
    }
    /**
     * 订单
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function cartCommit(Request $request)
    {
        $carts = $request->json;
        if(!$carts || empty($carts))return redirect()->back()->with('success', translate('请选择商品'));
        if(strstr($carts, ','))
        {
            $carts_arr = explode(',', $carts);
        }else{
            $carts_arr = [$carts];
        }
        $List = GoodsShopcar::whereIn('id', $carts_arr)->get();

        $total = sumTotal($List);
        //获取收货地址
        if(!$request->address)
        {
            $address = Address::where('user_id', Auth::user()->id)->where('is_default', '1')->first();
        }else{
            $address = Address::where('user_id', Auth::user()->id)->find($request->address);

            if(!$address)$address = Address::where('user_id', Auth::user()->id)->where('is_default', '1')->first();
        }

        //存入session,保存订单信息，选取地址后重新请求
        $key = '_session_carts';
        session([$key=> $carts]);

        return view('user.cartcommit', compact('List', 'total', 'address'));
    }
    /**
     * 用户收货地址
     * @param Request $request
     */
    public function toAddress(Request $request)
    {
        if($request->isMethod('post')){
            if($request->id>0 && $request->type=='default')
            {
                Address::where('user_id', Auth::user()->id)->update(['is_default'=>0]);
                Address::where('id', $request->id)->where('user_id', Auth::user()->id)->update(['is_default'=>1]);
                return ['msg'=> translate('更新成功')];
            }elseif ($request->id>0 && $request->type=='del'){
                Address::where('user_id', Auth::user()->id)->where('id', $request->id)->delete();
                return ['status'=> 1];
            }
        }
        $type= 0;
        if($request->type == 1)
        {
            $type = 1;
        }
        $pageList = Address::where('user_id', Auth::user()->id)->orderBy('is_default', 'desc')->orderBy('id', 'desc')->paginate(50);
        $pageList->everypage = 50;
        return view('user.address', compact('pageList','type'));
    }
    /**
     * 增加地址/地址详情
     * @param Request $request
     * @return string[]|\Illuminate\Contracts\Translation\Translator[]|NULL[]
     */
    public function toAddressDetail(Request $request)
    {
        $info = [];
        if($request->id >0 )
        {
            $info = Address::where('user_id', Auth::user()->id)->find($request->id);
        }
        if($request->isMethod('post')){
            if(!$info)
            {
                $info = new Address();
            }
            if($request->is_default == 1)
            {
                Address::where('user_id', Auth::user()->id)->update(['is_default'=>0]);
                $info->is_default = 1;
            }
            $info->name = $request->name;
            $info->address = $request->address;
            $info->code = $request->code;
            $info->mobile = $request->mobile;
            $info->user_id = Auth::user()->id;
            $info->save();
            return ['msg'=> translate('保存成功')];
        }

        return view('user.detailaddress', compact('info'));
    }

    public function createPay(Request $request)
    {
        $goods = $request->goods;
        if(!$goods || empty($goods))return ['status'=>0, 'msg'=> translate('请选择商品')];
        $address_id = (int)$request->address_id;
        if($address_id <=0)return ['status'=>0, 'msg'=> translate('请选择地址')];
        //计算商品价格
        $carts_arr = [];
        $order_number = 0;
        foreach ($goods as $row)
        {
            $carts_arr[] = $row['goods_attr_id'];
        }
        $List = GoodsShopcar::whereIn('id', $carts_arr)->get();
        if(!$List)return ['status'=>0, 'msg'=> translate('请选择商品')];
        $total = sumTotal($List);
        //创建订单
        $Order = new Order();
        $Order->user_id = Auth::user()->id;
        $Order->pay_price = $total;
        $Order->type = $request->buyway;
        $Order->address_id = $address_id;
        $Order->orders_number = $this->StrOrderOne();
        $Order->save();
        //创建订单商品关系
        $ordersData = [];
        $time = date('Y-m-d H:i:s');

        foreach ($List as $row)
        {
          if(intval($row->goods_id) <= 0)continue;
          if(intval($row->goods_attr_id) <= 0)continue;
            $ordersData[] = [
                'orders_id' => $Order->id,
                'goods_attr_id' => $row->goods_attr_id,
                'goods_id' => $row->goods_id,
                'goods_num' => $row->number,
                'content' => $row->content,
                'goods_price' => $row->goods_attr->price,
                'status' => 1,
                'created_at' => $time,
                'updated_at' => $time,
            ];
        }
        if(empty($ordersData))return ['status'=>0, 'msg'=> translate('订单商品不能为空')];
        $OrdersGood = new OrdersGood();
        $OrdersGood->insert($ordersData);
        //删除购物车
        foreach ($List as $row)
        {
            $row->status = 2;
            $row->save();
        }
        return ['status'=>1, 'msg'=> translate('创建订单成功')];

    }




    /**
     * 保存资料
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function toInfo(Request $request)
    {
        if($request->isMethod('post')){
            $data = $request->all();
            $user = Auth::user();
            $user->realname = $data['realname'];
            $user->nickname = $data['nickname'];
            $user->email = $data['email'];
            $user->sex = $data['sex'];
            $user->birthday = $data['birthday'];
            $user->save();
            return redirect()->back()->with('status', 1);
        }
        return view('user.info');
    }
    /**
     * 订单管理
     */
    public function toMyOrder(Request $request)
    {
        if($request->isMethod('post')){
          $info = Order::where('user_id', Auth::user()->id)->where('status', 3)->where('id', $request->id)->firstOrFail();
          $info->status = 4;
          $info->save();
          return ['msg'=>  translate('确认成功')];
        }
        $status = $request->status;
        if(!isset($request->status)) $status = 1;
        if(!isset($request->page)) $request->page= 1;

        $pageList = Order::where('user_id', Auth::user()->id)->where('status', $status)->orderBy('id', 'desc')->paginate(10);
        $pageList->everypage = 10;

        if($request->ajax == 1)
        {
            $data = [];
            $data['view'] = view('user.orderlist', compact('pageList'))->render();
            $data['current_page'] = $request->page;
            return $data;
        }

        return view('user.order', compact('pageList'));
    }

    /**
     * 支付方式
     * @param Request $request
     */
    public function toChoose(Application $payment, Request $request)
    {

//session()->forget('wechat');
//return 1;
        $info = Order::where('user_id', Auth::user()->id)->where('status', 1)->where('is_pay', 0)->where('orders_number', $request->sequence)->firstOrFail();

        //var_dump($request->isMethod('post'));
//return $request->post();
        if($request->isMethod('post'))
        {
          $user = session('wechat.oauth_user');

      		if(!$user)
      		{
      			$app = app('wechat.official_account');
      			$response = $app->oauth->scopes(['snsapi_base'])->redirect();
      			return $response;
      		}
      		$user_arr = $user['default']->toArray();

          $this->payAll($request, $user_arr, $info, $payment);

        }
        return view('user.choose', compact('info'));
    }

    protected function payAll($request, $user_arr, $info, $payment)
    {
      $info->out_trade_no = $this->StrOrderOne();
      $info->sve();
      if($request->test == 0)
      {
          if(!is_weixin())return redirect()->back()->with('success', translate('请用微信打开支付'));
  $data = [
        'body' => '桔子屋-支付',
    'openid' => $user_arr['id'],
    // 'out_trade_no' => str_random(20),
        'out_trade_no' => $info->out_trade_no,
        'total_fee' => sumTotal($info->orders_goods)*100 + $info->ems_price*100,
        'spbill_create_ip' => $request->getClientIp(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
        'trade_type' => 'JSAPI'
      ];
      $result = $payment->order->unify($data)->toArray();
      //dd($result);
      if(isset( $result['result_code']) && $result['result_code'] == 'SUCCESS' && isset($result['return_code']) && $result['return_code'] == 'SUCCESS')
      {

        //插入记录表
        $RechargeRecord = new RechargeRecord();
        $RechargeRecord->user_id = Auth::user()->id;
        $RechargeRecord->content = json_encode($result);
        $RechargeRecord->money = $info->pay_price;
        $RechargeRecord->out_trade_no = $data['out_trade_no'];
        $RechargeRecord->type = 'wechat';
        $RechargeRecord->save();
    $jssdk = $payment->jssdk;
    $json = $jssdk->bridgeConfig($result['prepay_id']);

        return redirect()->back()->with('json', $json)->with('ssss', 'ssssss');
      }else {

        return redirect()->back()->with('success', $result['return_msg'].$result['err_code_des']);
      }

      }
    }


    public function toAlterPass(Request $request)
    {
        if($request->isMethod('post'))
        {
            $this->validate($request, [
                    'oldpassword'=>'required',
                    'password'=>'required|min:6|confirmed',
                    'password_confirmation' => 'required|min:6'
                ], ['required'=> translate('全部必须填写'),'confirmed' => translate('两次密码不一致'), 'min' => '密码不小于6位']);
                $userinfo = User::where('id', Auth::user()->id)->firstOrFail();

                if(\Hash::check(\Request::input('oldpassword'), $userinfo->password))
                {
                    $userinfo->password = bcrypt($request->password);
                    $userinfo->save();
                    return redirect()->back()->with('status', 1);
                }else {
                    return redirect()->back()->with('success', translate('密码错误'));
                }


        }
        return view('user.password');
    }





	/**
     * 删除名片
     * @param unknown $id
     */
    public function deleteCart($id)
    {
        $service = Cart::findOrFail($id);
        $service->delete();
        return redirect()->back()->with('status', '删除成功.');
    }
    /**
     *
     */

    /**
     * 需求发布
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function sendService(Request $request)
    {
        if($request->isMethod('post'))
        {
            $this->validate($request, [
                'title'=>'required',
                'content'=>'required',
            ], ['required'=>'必须填写.']);
            $service = new Service();
            $service->title = $request->title;
            $service->type = $request->type;
            $service->user_id = Auth::user()->id;
            $service->remark = $request->remark;
            $service->content = htmlspecialchars($request->content);
            $service->save();
            return redirect()->back()->with('status', '新增成功.');
        }
        return view('user.sendservice');
    }

    /***
     * 我的需求
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
     */
    public function myService()
    {
        $pageList = Service::where('user_id', Auth::user()->id)->orderBy('id', 'desc')->paginate(15);
        $pageList->everypage = 15;
        return view('user.myservice', compact('pageList'));
    }
    /**
     * 删除需求
     * @param unknown $id
     */
    public function deleteService($id)
    {
        $service = Service::findOrFail($id);
        $service->delete();
        return redirect()->back()->with('status', '删除成功.');
    }
    /**
     *
     */
    public function dataCenter(Request $request)
    {Auth::guard()->logout();

        $request->session()->invalidate();
        $pageList = Facebook::where('user_id', Auth::user()->id)->orderBy('id', 'desc')->paginate(15);
        $pageList->everypage = 15;
        return view('user.datacenter', compact('pageList'));
    }
    /**
     * 查看留言以及发布留言
     * @param Request $request
     * @return unknown|string|\Illuminate\Http\RedirectResponse
     */
    public function facebook(Request $request)
    {
        if($request->isMethod('post') && $request->id > 0)
        {
            $res = Facebook::where('user_id', Auth::user()->id)->where('id', $request->id)->first();
            if($res)
            {
                return $res;
            }else {
                return $res['replay'] = '暂无数据.';
            }
        }
        $this->validate($request, [
            'name'=>'required',
            'email'=>'required',
            'company'=>'required',
            'mobile'=>'required',
            'content'=>'required',
            'code' => 'required|size:5|captcha'
        ], ['required'=>'全部必须填写.','code.required' => '验证码必须填写.',
            'code.size' => '验证码长为:size.',
            'code.captcha' => '验证码错误,请点击验证码刷新.',]);
        $service = new Facebook();
        $service->name = $request->name;
        $service->email = $request->email;
        $service->company = $request->company;
        $service->mobile = $request->mobile;
        $service->user_id = Auth::user()->id;
        $service->content = htmlspecialchars($request->content);
        $service->save();
        return redirect()->back()->with('status', '新增成功.');
    }
    /**
     * 用户发送名片
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function sendCart(Request $request)
    {
        if($request->isMethod('post'))
        {
            $this->validate($request, [
                'company'=>'required',
                'name'=>'required',
                'fname'=>'required',
                // 'mobile'=>'required',
                // 'homepage'=>'required',
                'price'=> 'required',
                'content'=>'required',
                'smetas'=>'required',
				// 'remark'=>'required',
            ], ['required'=>'请填写必须填写项.']);
            //处理上传图片
            $res = $this->uploadFilesSmeta($request);

            $cart = new Cart();
            $cart->email = $request->email;
            $cart->company = $request->company;
            $cart->name = $request->name;
            // $cart->mobile = $request->mobile;
            $cart->fname = $request->fname;
            $cart->remark = $request->remark;
            $cart->catid = $request->catid;
            $cart->homepage = $request->homepage;
            $cart->price = $request->price;
            $cart->content = $request->content;
            $cart->attachment = $res;
            $cart->user_id = Auth::user()->id;
            $cart->save();
			//插入栏目关系表
			if(isset($request->catidr) && !empty($request->catidr))
			{
				$data = [];
				foreach($request->catidr as $row)
				{
					$id = intval($row);
					if($id >0)
					{
						$data[] = [
							'catid' => $id,
							'cart_id' => $cart->id,
						];
					}
				}
				if(!empty($data))
				{
					$CaitCart = CaitCart::insert($data);
				}
			}

            return redirect()->back()->with('status', '新增成功.');
        }
        return view('user.sendcart');
    }

    /**
     * 资料以及名片购买
     * @param Request $request
     * @return number[]|string[]
     */
    public function buy(Request $request)
    {
        $this->validate($request, [
            'item_id'=>'required',
            'item_type'=>'required'
        ], ['required'=>'请填写必须填写项.']);

        if($request->item_type == 'cart')
        {
            $model = Cart::where('id', $request->item_id)->first();
        }elseif($request->item_type == 'article') {
            $model = Article::where('id', $request->item_id)->first();
        }
        if(!$model)
        {
            return [
                'status' => 0,
                'msg' => '不存在.'
            ];
        }
        if($model->price <=0)
        {
            return [
                'status' => 0,
                'msg' => '此项目不需要购买，免费观看.'
            ];
        }
        //判断用户是否已经购买
        if(Buy::where('item_id', $request->item_id)->where('item_type', $request->item_type)->where('user_id', Auth::user()->id)->first())
        {
            return [
                'status' => 0,
                'msg' => '您已经购买，请勿重复购买，刷新后观看.'
            ];
        }
        //判断用户余额
        if(Auth::user()->money < $model->price)
        {
            return [
                'status' => 1,
                'msg' => '余额不足，请去充值.'
            ];
        }
        //增加购买记录
        $buy = new Buy();
        $buy->item_id = $request->item_id;
        $buy->item_type = $request->item_type;
        $buy->user_id = Auth::user()->id;
        $buy->money = $model->price;
        $buy->item_id = $request->item_id;
        $buy->save();
        //减去金额
        Auth::user()->decrement('money', $model->price);
		if($request->item_type == 'cart')//为名片购买的时候 计算收益
		{
			//个人收益
			$m = round($model->price*(1-config('kou')),2);
			User::find($model->user_id)->increment('money', $m);
			$log = new MoneyLog();
			$log->user_id = $model->user_id;
			$log->money = $m;
			$log->item_id = $request->item_id;
			$log->item_type = $request->item_type;
			$log->content = '用户购买您的名片['.$model->company.']收入.'.$m.'元';
			$log->save();
			//平台收益记录
			$log = new MoneyLog();
			$log->user_id = 15;
			$log->money = $model->price - $m;
			$log->item_id = $request->item_id;
			$log->item_type = $request->item_type;
			$log->content = '用户购买名片['.$model->company.']收入.'.$log->money.'元';
			$log->save();
		}elseif($request->item_type == 'article')
		{
			//平台收益记录
			$log = new MoneyLog();
			$log->user_id = 15;
			$log->money = $model->price;
			$log->item_id = $request->item_id;
			$log->item_type = $request->item_type;
			$log->content = '用户购买报告下载['.$model->post_title.']收入.'.$model->price.'元';
			$log->save();
		}


        //插入用户金额表
        $log = new MoneyLog();
        $log->user_id = Auth::user()->id;
        $log->money = '-'.$model->price;
        $log->item_id = $request->item_id;
        $log->item_type = $request->item_type;
        $log->content = '购买商品支付.'.$model->price.'元';
        $log->save();



        return [
            'status' => 2,
            'msg' => '购买成功.'
        ];

    }
    /**
     * 展示名片
     * @param Request $request
     * @return number[]|string[]|number[]|string[]|number[][]|NULL[][]|unknown[][][][]
     */
    public function showCart(Request $request)
    {
        $this->validate($request, [
            'item_id'=>'required',
            'item_type'=>'required'
        ], ['required'=>'请填写必须填写项.']);

        if($request->item_type == 'cart')
        {
            $model = Cart::where('id', $request->item_id)->first();
            if(!$model && !$model->buys && $model->user_id != Auth::user()->id && $model->price > 0)
            {
                return [
                    'status' => 0,
                    'msg' => '请购买后查看.'
                ];
            }
            $data = [];
            foreach ($model->attachment as $row)
            {
                $data[] = [
                    'alt' => $row['originalName'],
                    'pid' => $row['filename'],
                    'src' => url($row['url']),
                    'thumb' => url($row['url'])
                ];
            }
            $json = [
                'title' => $model->title,
                'id' => $model->id,
                'start' => 0,
                'data' => $data
            ];
            return [
                'status' => 1,
                'data' => $json,
                'msg' => 'ok.'
            ];
        }else {
            return [
                'status' => 0,
                'msg' => '参数错误.'
            ];
        }
    }


    /**
     * 我的名片
     */
    public function buyRecord()
    {
        $pageList = Buy::where('user_id', Auth::user()->id)->orderBy('id', 'desc')->paginate(15);
        $pageList->everypage = 15;
        return view('user.buyrecord', compact('pageList'));
    }

    public function reCharge(Application $payment, Request $request)
    {
        if($request->isMethod('post'))
        {

            $this->validate($request, [
            'money'=>'required|numeric|min:0',
            'type'=> [
                    'required',
                    \Illuminate\Validation\Rule::in(['1', '2']),
                ]
            ], ['money.required'=>'金额必须填写.','numeric'=> '金额必须大于50.']);
            if($request->type==1)//微信
            {
                $data = [
        					'body' => '纺织名片宝-充值',
        					'out_trade_no' => $this->StrOrderOne(),
        					'total_fee' => $request->money*100,
        					'spbill_create_ip' => $request->getClientIp(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
        					'trade_type' => 'NATIVE'
        				];
        				$result = $payment->order->unify($data);
        				// dd($result);
        				if(isset( $result['result_code']) && $result['result_code'] == 'SUCCESS' && isset($result['return_code']) && $result['return_code'] == 'SUCCESS')
        				{
        					//插入记录表
        					$RechargeRecord = new RechargeRecord();
        					$RechargeRecord->user_id = Auth::user()->id;
        					$RechargeRecord->content = json_encode($result);
        					$RechargeRecord->money = $request->money;
        					$RechargeRecord->out_trade_no = $data['out_trade_no'];
        					$RechargeRecord->type = 'wechat';
        					$RechargeRecord->save();

        					return redirect()->back()->with('wechaturl', $result['code_url'])->with('money', $request->money);
        				}else {
        					return redirect()->back()->with('status', $result['return_msg']);
        				}
            }elseif($request->type==2)//支付宝
            {
                $gateway = Omnipay::create('Alipay_AopPage');
                $gateway->setSignType('RSA2'); //RSA/RSA2
                $gateway->setAppId('2018030702330598');
                $gateway->setPrivateKey('MIIEowIBAAKCAQEAx/YWKgJyyKs84biLID/YB7YhCuotaGDma1YxFb8+p0j8Tj2XmOH+5B2Emrkj+FFS9eU4hNPbAcgw6g6weBEJKGf+kO7nR7Wd6VZ04/ciVp8rUR2OUemxItVyw9kWoLjcSdY2Pvw+xun2LCauuid3tU6ev/WvJFwQCRYELvXBP/xED2PDwiRuA4QCIN43b/TMW6T1OxSSIF7BG6TNmsViWRw1A/9E8vS/u4+rrlSwMSw+WbGzHlyefD07yZIdKEP1ywPWyCJ+J7K51k4z71n9LTS/K6NP6iuFLtDsVBC+fgfdiTZFZxbtPrhKgDbRu8X9R16Ozlj8Vu7xq4ZWXMuaVQIDAQABAoIBAEWrVhmY9Mk58GJs2/yGggxdxrF42g1OBbpMM5nyIjBC27We/BzGUPrF1hfafc/c9dy62rBc6Cd8yp4iNBYBSYGMikORGYAApV5RQzTSPGKV3o/KjnW3yIHsgKoAD0Q8ZHRNcGUNmgnQJndHmwU9DxZaqDEVtsoiUWv5Acgi1AwoiLtpSeGx3jzsonODpB5wgU9rV9SzTIxazFkIC8+kAz+v7GNw8OGF3jJYFz1J9cludD12ZmxnH0u6m85x0rhoII2J4qeOLKeyRSLlzIw6eG58jQqWXe7xWD7MwIfJpZnxbEXK9cEwUvrdwgU4yQS/D60CVBhGSsDuELf7c1oZLtkCgYEA8ob/aHOILvrXfeBe50JhwCTEoitplQhp4cLgK30meZmP5HulQyGwDtVgsWRRW947P0pNkYD6nRxLGOVA0LZHO0H9y7I1LjITsiSXI7B0oMn5B3F0q2d6TiIqBT7II/NWjWkmFtQna/V6lQn24eatH8H/I2r0dG0oCE0UQdyHgzcCgYEA0xHA1fh8z3MazGgShbj4J4xpW6YLWPDb0YOL072b08lPrshJRrHePqzvZD5LfvqSISp+Nc8CZfnVfDwKEjBBvCdHM5Za3gf5m8K5MyhTyQmNykISBoFmWs/gEM5E1/CR5XggMmJYPVT7dlS9v3jN7IVfaDhKu7fmVGoUw6ZbLNMCgYAZo0u8rvnmfX3qQJ3HtKzAsyJWQmCW8JzA0OkBr+kxUZp0fN2rixQhfU0Lc59mJsf8mM46Y3gaw7Lsns+LQLmm+gLqVZxplcGfQ1721uB9XtyEfOnodLfpKpNmmoxtwHuV11e/cg34y6p5tuPyXYBPqyJdjCDrbd6dgghyLe3lYQKBgQDMyF/A+gsWNwZcJek6pqDVtiyOiAZgb6fGmguzDza9/4Z4/MfjeDU5uA23w5z6AOCAnzq+uC8Kg5/2nkXjKcDNbYpuacWVwEUUM5P+J3VLCyLvhrT4bNnC6AbsJ0SyAi17ZtZOLA6Syv4C6+sBd5LLlQdhFaSkhqNJaXbl8GRrkwKBgDWKq+bK+sdC+WX/V2pNPWe23/pIB94Tuqr2zkNha3aW4guHo1QUUHrdPCOt3zj3OJU1EXtA7ZSIFcyFNBsDbORK57/93ayKyDewpkc4Z+oDAelt7+nyTGiKSKJF05wIizZ/z5ika0oTa04zmfhiqBrPpuZAMcnccsSTk6xNdWrM');
                $gateway->setAlipayPublicKey('MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx/YWKgJyyKs84biLID/YB7YhCuotaGDma1YxFb8+p0j8Tj2XmOH+5B2Emrkj+FFS9eU4hNPbAcgw6g6weBEJKGf+kO7nR7Wd6VZ04/ciVp8rUR2OUemxItVyw9kWoLjcSdY2Pvw+xun2LCauuid3tU6ev/WvJFwQCRYELvXBP/xED2PDwiRuA4QCIN43b/TMW6T1OxSSIF7BG6TNmsViWRw1A/9E8vS/u4+rrlSwMSw+WbGzHlyefD07yZIdKEP1ywPWyCJ+J7K51k4z71n9LTS/K6NP6iuFLtDsVBC+fgfdiTZFZxbtPrhKgDbRu8X9R16Ozlj8Vu7xq4ZWXMuaVQIDAQAB');
                $gateway->setReturnUrl('http://www.textile-cards.com/user/reCharge');
                $gateway->setNotifyUrl('http://www.textile-cards.com/alipay/notify_url');


				$requests = $gateway->purchase();
				$out_trade_no = $this->StrOrderOne();
				$requests->setBizContent([
					'out_trade_no' => $out_trade_no,
					'total_amount' => $request->money,
					'subject'      => '用户['.Auth::user()->mobile.']充值.'.$request->money.'元',
					'product_code' => 'FAST_INSTANT_TRADE_PAY',
				]);

				/**
				 * @var AopCompletePurchaseResponse $response
				 */
				$response = $requests->send();

				//插入记录表
				$RechargeRecord = new RechargeRecord();
				$RechargeRecord->user_id = Auth::user()->id;
				$RechargeRecord->content = json_encode($response);
				$RechargeRecord->money = $request->money;
				$RechargeRecord->out_trade_no = $out_trade_no;
				$RechargeRecord->type = 'alipay';
				$RechargeRecord->save();



				$redirectUrl = $response->getRedirectUrl();
				//or
				$response->redirect();

            }else{
                return redirect()->back()->with('status','支付出错，请稍后再试.');
            }


        }
        return view('user.recharge');
    }


	public function inCome()
	{
		$pageList = MoneyLog::where('user_id', Auth::user()->id)->where('item_type', 'cart')->where('money', '>', 0)->orderBy('id', 'desc')->paginate(15);
        $pageList->everypage = 15;
        return view('user.income', compact('pageList'));
	}

	public function withdraw(Request $request)
	{
		if($request->isMethod('post'))
        {

            $this->validate($request, [
            'money'=>'required|numeric|min:50',
			'mobile'=>'required',
			'name'=>'required',
			'account'=>'required',
            'accounttype'=> [
                    'required',
                    \Illuminate\Validation\Rule::in(['1', '2']),
                ]
            ], ['required'=>'请填写全部填写项.','numeric'=>'必须填写数字','min'=> '金额必须大于50.']);
			//判断余额
			if(Auth::user()->money < (int)$request->money)
			{
				return redirect()->back()->with('status','余额不足.');
			}
			//判断正确申请的提现
			if(Withdraw::where('status', 0)->where('user_id', Auth::user()->id)->first())
			{
				return redirect()->back()->with('status','您已经提现，请耐心等待.');
			}

			$Withdraw = new Withdraw();
			$Withdraw->mobile = $request->mobile;
			$Withdraw->name = $request->name;
			$Withdraw->account = $request->account;
			$Withdraw->accounttype = $request->accounttype;
			$Withdraw->money = (int)$request->money;
			$Withdraw->user_id = Auth::user()->id;
			$Withdraw->save();

            return redirect()->back()->with('status','申请成功，系统将在1-2工作日内处理.');



        }
		return view('user.withdraw');
	}

	public function withdrawRecord()
	{
		$pageList = Withdraw::where('user_id', Auth::user()->id)->orderBy('id', 'desc')->paginate(15);
        $pageList->everypage = 15;
        return view('user.withdraw1', compact('pageList'));
	}


	/**
     * 生成订单号
     * @return string
     */
    protected function StrOrderOne(){
        return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }

    /**
     * 上传图片
     * @param unknown $request
     */
    protected function uploadFilesSmeta(Request $request)
    {
        $result = [];
        if ($request->hasFile('smetas')) {
            //
            $files     = $request->file('smetas');
            $disk = Storage::disk('admin');
            foreach ($files as $file)
            {
                if ($file->isValid()) {

                    // 获取文件相关信息
                    $originalName = $file->getClientOriginalName();
                    $ext          = $file->getClientOriginalExtension();
                    $realPath     = $file->getRealPath();
                    $type         = $file->getClientMimeType();
                    $filename     = md5(uniqid()) . '.' . $ext;

                    $bool         = $disk->put('cart/'.$filename, file_get_contents($realPath));

                    if ($bool) {
                        $result[] = [
                            'url' => ('upload/cart/' . $filename),
                            'ext' => $ext,
                            'type' => $type,
                            'originalName' => $originalName,
                            'filename' => $filename
                        ];
                    }
                }
            }
        }
        return $result;

    }
}
